#include "facedetectcilent.h"
#include "ui_facedetectcilent.h"
#include <QJsonDocument>
#include <QJsonObject>
faceDetectCilent::faceDetectCilent(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::faceDetectCilent)
{
    ui->setupUi(this);
    cascade.load("C:/Users/13275/Desktop/embedded_Project/mid_File/opencv-compile-Win/opencv_4.5.2/etc/haarcascades/haarcascade_frontalface_alt2.xml");
    cap.open(0);
    startTimer(100);
    connect(&tcpClient,&QTcpSocket::connected,this,&faceDetectCilent::socket_Connect);
    connect(&tcpClient,&QTcpSocket::disconnected,this,&faceDetectCilent::socket_DisConnect);
    connect(&mtime,&QTimer::timeout,this,&faceDetectCilent::timeFunct);
    connect(&tcpClient,&QTcpSocket::readyRead,this,&faceDetectCilent::recv_data);
    mtime.start(3000);
}

faceDetectCilent::~faceDetectCilent()
{
    delete ui;
}

void faceDetectCilent::timerEvent(QTimerEvent *e)
{
    // 1、opencv 的bgr 图片
   Mat imagemat;
   if(cap.grab())
   {
       cap.read(imagemat);
   }

   Mat grayimg;
   cvtColor(imagemat,grayimg,COLOR_BGR2GRAY);
   vector<Rect> facerects;

   cascade.detectMultiScale(grayimg,facerects);
   if(facerects.size()>0)
   {
       Rect r1 = facerects.at(0);
       ui->headlb->move(r1.x,r1.y);

       //发送数据到服务器
       vector<uchar> buf;
       imencode(".jpg",imagemat,buf);
       QByteArray msg((const char *)buf.data(),buf.size());
       quint64 len = buf.size();
       QByteArray senddata;
       QDataStream stream(&senddata,QIODevice::WriteOnly);
       stream.setVersion(QDataStream::Qt_5_14);
       stream<<len<<msg;
       tcpClient.write(senddata);



   }else{
       ui->headlb->move(100,60);
       ui->name->clear();
       ui->number->clear();
       ui->part->clear();
       ui->time->clear();
   }
   // 2、将bgr -> bgr
   cvtColor(imagemat,imagemat,COLOR_BGR2RGB);
   // 3、将opencv的图片格式变为Qt的图片数据格式
   QImage qimg(imagemat.data,imagemat.cols,imagemat.rows,imagemat.step1(),QImage::Format_RGB888);
   // 4、加载处理图片的类
   QPixmap piximg = QPixmap::fromImage(qimg);
   //QImage img = imread()
   ui->videolb->setPixmap(piximg);
}

void faceDetectCilent::timeFunct()
{
    qDebug()<<"connect-ing"<<endl;
    tcpClient.connectToHost("172.21.18.37",777);
}

void faceDetectCilent::socket_Connect()
{
    qDebug()<<"connect-stop"<<endl;
    mtime.stop();
}

void faceDetectCilent::socket_DisConnect()
{
    qDebug()<<"connect-restart"<<endl;
    mtime.start(3000);
}

void faceDetectCilent::recv_data()
{
    QByteArray str = tcpClient.readAll();

    QJsonDocument jsons = QJsonDocument::fromJson(str);
    QJsonObject jsono = jsons.object();
    ui->name->setText(jsono["name"].toString());
    ui->number->setText(jsono["job"].toString());
    ui->part->setText(jsono["part"].toString());
    ui->time->setText(jsono["time"].toString());
}

